<template>
  <el-dialog
    :title="isEdit ? '修改任务' : '分配任务'"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      

      <!-- 分配任务时才显示部门和负责人选择 -->
      <template v-if="!isEdit">
        <!-- 在标题输入框前添加任务选择 -->
      <el-form-item label="关联任务" prop="taskId">
        <el-select
          v-model="form.id"
          filterable
          placeholder="请选择或搜索任务(可选，非必填)"
          clearable
          @change="handleTaskSelect"
          class="uniform-input"
        >
          <el-option
            v-for="task in taskOptions"
            :key="task.value"
            :label="task.label"
            :value="task.value"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="负责人" prop="responsibleUserId">
          <el-select 
            v-model="form.responsibleUserId" 
            placeholder="请选择负责人"
            filterable
            class="uniform-input"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.realname"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </template>

      
      <el-form-item label="标题" prop="title">
        <el-input 
          v-model="form.title" 
          placeholder="请输入任务标题"
          class="uniform-input"
        />
      </el-form-item>

      <el-form-item label="预计时间" prop="estimatedTime">
        <div class="date-picker-wrapper">
          <el-date-picker
            v-model="form.estimatedTime"
            type="datetime"
            placeholder="选择预计完成时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </el-form-item>
      <el-form-item label="完成时间" prop="completedTime">
        <div class="date-picker-wrapper">
          <el-date-picker
            v-model="form.completedTime"
            type="datetime"
            placeholder="选择实际完成时间（可选）"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select 
          v-model="form.state" 
          placeholder="请选择状态"
          class="uniform-input"
        >
          <el-option
            v-for="option in stateOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <!-- 添加状态修改说明 -->
      <el-form-item label="修改说明" prop="stateReason">
        <el-input
          v-model="form.stateReason"
          type="textarea"
          :rows="2"
          placeholder="请输入状态修改说明"
          class="full-width"
        />
      </el-form-item>

      <el-form-item label="任务内容" prop="description">
        <RichTextEditor 
          v-model="form.description"
          :on-image-upload="handleMediaUpload"
        />
      </el-form-item>

      <!-- 隐藏的 dailyId 字段 -->
      <el-form-item prop="dailyId" style="display: none;">
        <el-input v-model="form.dailyId" type="hidden" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import RichTextEditor from './RichTextEditor.vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  taskData: Object,  // 用于修改时的数据
  reportData: Object, // 用于分配任务时的数据
  isEdit: Boolean    // 是否是编辑模式
})

const emit = defineEmits(['update:visible', 'submit', 'refresh'])

const dialogVisible = ref(false)
const formRef = ref(null)
const allUsers = ref([]) // 存储所有用户
const userOptions = ref([]) // 显示的用户列表
const taskOptions = ref([])

// 表单数据
const form = ref({
  id: '',
  responsibleUserId: '',
  title: '',
  description: '',
  estimatedTime: '',
  completedTime: null,
  dailyId: '',
  state: 1,  // 默认为待处理状态
  stateReason: '',  // 添加状态修改说明字段
})

// 表单验证规则
const rules = {
  responsibleUserId: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  estimatedTime: [{ required: true, message: '请选择预计完成时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入任务内容', trigger: 'blur' }],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }],
  stateReason: [
    { required: true, message: '请输入状态修改说明', trigger: 'blur' }
  ],
  taskId: [{ required: false, message: '请选择任务', trigger: 'change' }]
}
// 修改状态选项为对象格式
const stateOptions = ref([
  { value: 1, label: '待处理' },
  { value: 2, label: '进行中' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已关闭' }
])

// 获取所有用户
const fetchInitialData = async () => {
  try {
    // 获取所有用户
    const userResponse = await axios.get('/user/queryAll')
    if (userResponse.data.code === 1) {
      allUsers.value = userResponse.data.data
      userOptions.value = allUsers.value // 默认显示所有用户
    }
  } catch (error) {
    console.error('获取初始数据失败:', error)
  }
}

// 获取所有任务
const fetchAllTasks = async () => {
  try {
    const response = await axios.get('/task/queryAll')
    if (response.data.code === 1) {
      taskOptions.value = response.data.data.map(task => ({
        value: task.id,
        label: task.title
      }))
    } else {
      ElMessage.error('获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  }
}

// 处理任务选择
const handleTaskSelect = async (taskId) => {
  console.log('选择的taskId:', taskId)  // 添加调试日志
  
  if (!taskId) {
    // 只有当明确点击清空时才重置表单
    if (taskId === null) {
      form.value = {
        id: '',
        responsibleUserId: '',
        title: '',
        description: '',
        estimatedTime: '',
        completedTime: null,
        dailyId: '',
        state: 1,
        stateReason: ''
      }
    }
    return
  }

  try {
    const response = await axios.get(`/task/task/${taskId}`)
    if (response.data.code === 1) {
      const taskDetail = response.data.data
      debugger
      // 填充所有表单数据
      form.value = {
        id: taskDetail.id,
        responsibleUserId: taskDetail.responsibleUserId,
        title: taskDetail.title,
        description: taskDetail.description,
        estimatedTime: taskDetail.estimatedTime,
        completedTime: taskDetail.completedTime,
        dailyId: taskDetail.dailyId,
        state: taskDetail.state,
        stateReason: taskDetail.stateReason
      }
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
  }
}

// 修改提交处理
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const url = props.isEdit ? '/task/update' : '/task/save'
    
    // 根据是否是编辑模式准备不同的提交数据
    const submitData = props.isEdit ? {
      // 编辑模式不需要 dailyId
      id: form.value.id,
      title: form.value.title,
      description: form.value.description,
      estimatedTime: form.value.estimatedTime,
      completedTime: form.value.completedTime,
      responsibleUserId: form.value.responsibleUserId,
      state: form.value.state,
      stateReason: form.value.stateReason
    } : {
      // 新增模式必须带 dailyId
      ...form.value,
      dailyId: props.reportData?.id  // 确保从 reportData 中获取 dailyId
    }

    const response = await axios.post(url, submitData)
    if (response.data.code === 1) {
      ElMessage.success(props.isEdit ? '修改成功' : '添加成功')
      emit('update:visible', false)
      emit('refresh')
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('表单验证失败')
  }
}

// 处理关闭
const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

// 监听 visible 变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    if (props.isEdit && props.taskData) {
      // 编辑模式，回显任务数据
      form.value = {
        id: props.taskData.id,
        title: props.taskData.title,
        description: props.taskData.description,
        estimatedTime: props.taskData.estimatedTime,
        completedTime: props.taskData.completedTime,
        responsibleUserId: props.taskData.responsibleUserId,
        state: props.taskData.state,
        stateReason: props.taskData.stateReason
      }
    } else if (props.reportData) {
      // 分配任务模式
      form.value = {
        title: props.reportData.title || '',
        description: props.reportData.content || '',
        dailyId: props.reportData.id || '',
        responsibleUserId: '',
        estimatedTime: '',
        completedTime: null,
        state: 1,
        stateReason: ''
      }
    }
  }
})

// 监听 dialogVisible 变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

onMounted(() => {
  fetchInitialData()
  fetchAllTasks()
})
</script>

<style>
/* 使用全局样式，不加 scoped */
.el-dialog {
  background: #ffffff !important;
}

.el-dialog__body {
  background: #ffffff !important;
}

.el-dialog__header {
  background: #ffffff !important;
}

.el-dialog__footer {
  background: #ffffff !important;
}
</style>

<style scoped>
/* 保留原有的 scoped 样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-picker) {
  width: 100%;
}

.uniform-input {
  width: 50% !important;
  height: 40px;
}

:deep(.el-input__wrapper),
:deep(.el-select),
:deep(.el-date-editor.el-input),
:deep(.el-date-editor) {
  height: 40px;
  line-height: 40px;
  width: 100%;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor),
:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}

:deep(.el-select .el-input__wrapper) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-date-editor .el-input__wrapper) {
  height: 40px;
  line-height: 40px;
  padding: 0 12px;
}

/* 添加统一的输入框宽度样式 */
:deep(.uniform-input) {
  width: 50%;
}

/* 专门设置日期选择器的宽度 */
:deep(.el-date-picker.uniform-input) {
  width: 50% !important;  /* 使用 !important 覆盖 Element Plus 的默认样式 */
}

/* 确保日期选择器内部元素也遵循宽度设置 */
:deep(.el-date-picker .el-input__wrapper) {
  width: 100%;
}

:deep(.el-date-picker .el-input) {
  width: 100%;
}

.date-picker-wrapper {
  width: 50%;  /* 设置包装器宽度 */
}

:deep(.date-picker-wrapper .el-date-picker) {
  width: 100%;  /* 日期选择器填充包装器 */
}

:deep(.date-picker-wrapper .el-input) {
  width: 100%;  /* 输入框填充包装器 */
}

:deep(.date-picker-wrapper .el-input__wrapper) {
  width: 100%;  /* 输入框包装器填充 */
}

/* 添加全宽样式 */
:deep(.full-width) {
  width: 100%;
}
</style> 